#include "i2cdevice.h"

#include <fcntl.h>
#include <stdio.h>
#include <linux/i2c-dev.h>
#include <stdlib.h>

I2CDevice::I2CDevice(int file, __u8 address)
{
  m_file = file;
  m_address = address;
}
I2CDevice::~I2CDevice() {}

void I2CDevice::acquireSlave()
{
  if (ioctl(m_file, I2C_SLAVE, m_address) < 0)
  {
      printf("I2C Device: Failed to acquire bus access and/or talk to slave device 0x%02X\n", m_address);
      exit(1);
  }
}

__s32 I2CDevice::writeByte(__u8 reg, __u8 val)
{
  acquireSlave();

  __s32 res;

  res = i2c_smbus_write_byte_data(m_file, reg, val);
  if (res < 0)
  {
    printf("I2C Device: Failed to write to slave device 0x%02X register 0x%02X\n", m_address, reg);
    exit(1);
  }
  return res;
}

__s32 I2CDevice::readByte(__u8 reg)
{
  acquireSlave();

  __s32 res; 

  res = i2c_smbus_read_byte_data(m_file, reg);
  if (res < 0)
  {
    printf("I2C Device: Failed to read from slave device 0x%02X register 0x%02X\n", m_address, reg);
    exit(1);
  }
  return res;
}

__s32 I2CDevice::readBlock(__u8 reg, __u8 * buf, int size)
{
  acquireSlave();

  __s32 res; 

  for (int i = 0; i < size; i++)
    buf[i] = 0;

  res = i2c_smbus_read_i2c_block_data(m_file, reg, size, buf);
  if (res != size)
  {
    printf("I2C Device: Failed to read %d bytes from slave device 0x%02X register 0x%02X\n", size, m_address, reg);
    exit(1);
  }
  return res;
}
